package com.itheima.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Order;
import com.itheima.pojo.Setmeal;
import com.itheima.service.OrderService;
import com.itheima.service.SetmealService;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.util.Map;

/**
 * 体检预约控制层
 * @author ：zengjie
 * @date ：2020/11/14
 */
@RestController
@RequestMapping("/order")
public class MobileOrderController {

    @Reference
    private OrderService orderService;

    @Reference
    private SetmealService setmealService;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 体检预约
     * {"setmealId":"12","sex":"1","telephone":"15111112222",
     * "idCard":"430426199904128952","validateCode":"1231"}
     * @param map
     * @return
     */
    @RequestMapping(value = "/submit",method = RequestMethod.POST)
    public Result submit(@RequestBody Map map){
        //进行验证码校验
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        String redisCode = jedisPool.getResource().get(RedisMessageConstant.SENDTYPE_ORDER + "_" + telephone);
        //验证码错误直接返回错误信息
        if (StringUtils.isEmpty(validateCode) || StringUtils.isEmpty(redisCode) || !validateCode.equals(redisCode)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //设置预约类型
        map.put("orderType", Order.ORDERTYPE_WEIXIN);
        return orderService.submit(map);
    }

    /**
     * 根据预约id查询预约信息
     */
    @RequestMapping(value = "/findById",method = RequestMethod.POST)
    public Result findById(Integer id){
        try {
            Map map = orderService.findById4Detail(id);//
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }

    /**
     * 生成PDF报表
     */
    @RequestMapping(value = "/exportSetmealInfo",method = RequestMethod.GET)
    public Result exportSetmealInfo(Integer id, HttpServletResponse response){
        try {
            //获取套餐id
            Map map = orderService.findById4Detail(id);
            Integer setmealId = (Integer) map.get("setmealId");
            //根据套餐id获取对应的检查组检查项
            Setmeal setmeal = setmealService.findById(setmealId);
            //Document 对象
            Document document = new Document();
            //设置文件类型
            response.setContentType("application/pdf");//pdf
            //设置文件名称
            response.setHeader("content-Disposition", "attachment;filename=orderPDF.pdf");

            PdfWriter.getInstance(document,response.getOutputStream());

            document.open();
            //设置字体
            BaseFont cn = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",false);
            Font font = new Font(cn, 10, Font.NORMAL, Color.BLUE);
            //插入体检信息
            document.add(new Paragraph("体检人："+map.get("member"),font));
            document.add(new Paragraph("体检套餐："+map.get("setmeal"),font));
            document.add(new Paragraph("体检日期："+map.get("orderDate").toString(),font));
            document.add(new Paragraph("预约类型："+map.get("orderType"),font));

            //创建表格对象
            Table table = new Table(3);
            table.setWidth(80); // 宽度
            table.setBorder(1); // 边框
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); //水平对齐方式
            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP); // 垂直对齐方式
            /*设置表格属性*/
            table.setBorderColor(new Color(0, 0, 255)); //将边框的颜色设置为蓝色
            table.setPadding(5);//设置表格与字体间的间距
//table.setSpacing(5);//设置表格上下的间距
            table.setAlignment(Element.ALIGN_CENTER);//设置字体显示居中样式
            //表头
            table.addCell(buildCell("项目名称",font));
            table.addCell(buildCell("项目内容",font));
            table.addCell(buildCell("项目备注",font));
            //循环插入检查项数据
            if(setmeal != null){
                for (CheckGroup checkGroup : setmeal.getCheckGroups()) {
                    //检查组名称
                    table.addCell(buildCell(checkGroup.getName(),font));

                    //检查项列表
                    StringBuffer sb = new StringBuffer();
                    for (CheckItem checkItem : checkGroup.getCheckItems()) {
                        String name = checkItem.getName();
                        sb.append(name+" ");
                    }
                    //检查项名称
                    table.addCell(buildCell(sb.toString(),font));
                    //检查组备注
                    table.addCell(buildCell(checkGroup.getRemark(),font));
                }
            }
            //将表格插入document对象
            document.add(table);
            document.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }
    // 传递内容和字体样式，生成单元格
    private Cell buildCell(String content, Font font)
            throws BadElementException {
        Phrase phrase = new Phrase(content, font);
        return new Cell(phrase);
    }
}
